/* 
增删改查 curd
1 查询全部数据
2 增加
    1 弹出和关闭 模态框  
        1 模态框弹出    用属性操控
            1 data-bs-toggle="modal"
            2 data-bs-target="#addModal"
        2 模态框关闭
        data-bs-dismiss="modal"
        2 JS操控
            1 $("模态框选择器").modal('show')
            2 $("模态框选择器").modal('hide')
    2 初始化 模态框中 省市区 三个组件
*/


//查询全部数据
async function getData(url, params) {
    const res = await axios({
        url: url,
        params,
    })
    if (params.id) {
        if (res.data.message === '未查到数据') return $('tbody').html(`${res.data.message}...`)
        const { id, name, age, sex, group, phone, salary, truesalary, province, city, county } = res.data.data
        $('tbody').html(
            `
            <tr>
            <th scope="row">${id}</th>
            <td>${name}</td>
            <td>${age}</td>
            <td>${sex}</td>
            <td>${group}</td>
            <td>${phone}</td>
            <td>${salary}</td>
            <td>${truesalary}</td>
            <td>${province + city + county}</td>
            <td>
                <button type="button" class="btn btn-primary btn-sm update-btn" data-id="${id}">修改</button>
                <button type="button" class="btn btn-danger btn-sm del-btn" data-id="${id}">删除</button>
            </td>
        </tr>
            `
        )
        return;
    }
    //遍历对象
    $('tbody').html(
        res.data.data.map(({ id, name, age, sex, group, phone, salary, truesalary, province, city, county }) => `
                <tr>
                    <th scope="row">${id}</th>
                    <td>${name}</td>
                    <td>${age}</td>
                    <td>${sex}</td>
                    <td>${group}</td>
                    <td>${phone}</td>
                    <td>${salary}</td>
                    <td>${truesalary}</td>
                    <td>${province + city + county}</td>
                    <td>
                        <button type="button" class="btn btn-primary btn-sm update-btn" data-id="${id}">修改</button>
                        <button type="button" class="btn btn-danger btn-sm del-btn" data-id="${id}">删除</button>
                    </td>
                </tr>
                `).join(''))
}
//省市区初始化渲染
initSelect()
//数据初始化渲染
getData('/student/list', {})

//封装 获取省市区
async function fetchRegion(url, params, text, target) {
    //操作省市区
    const res = await axios({ url, params, })
    $(`[name=${target}]`).html(res.data.reduce((prev, v) =>
        prev + `<option value="${v}">${v}</option>`, `<option value="">--${text}--</option>`))


}
//初始化省市区组件函数
async function initSelect() {
    await fetchRegion('/geo/province', {}, '省', 'province')
}
//省->市联动
$('[name=province]').on('change', async () => {
    await fetchRegion('/geo/city', {
        pname: $('[name=province]').val()
    }, '市', 'city')
    $(`[name="county"]`).html($(`[name="county"]`).children('option:first-child')[0].outerHTML)
    // console.log($(`[name="county"]`).children('option:first-child').html());
})
//市->县联动
$('[name=city]').on('change', async () => {
    await fetchRegion('/geo/county', {
        pname: $('[name=province]').val(),
        cname: $('[name=city]').val()
    }, '县', 'county')
})

//给form表单绑定提交事件
$('.add-form').on('submit', async function (e) {
    //获取表单
    const data = serialize($('.add-form')[0], { hash: true, empty: true }) //empty 空的字段也会被获取到
    //添加验证
    if ($('#addModalLabel').html() === '录入新学员') {
        delete data.id
    }
    //阻止默认提交
    e.preventDefault()
    for (const key in data) {
        if (!data[key]) {
            toastr.error('请检查你的字段', '提示')
            return
        }
    }
    console.log(data);
    //响应结果
    let response
    //修改学员验证
    if ($('#addModalLabel').html() === '修改学员') {
        //发送请求 修改学员
        response = await axios({ url: '/student/update', method: 'put', data })
    }
    //添加学员
    else if ($('#addModalLabel').html() === '录入新学员') {
        // delete data.id
        //发送请求 添加学员
        response = await axios({ url: '/student/add', method: 'post', data })
    }

    if (response.data.code === 0) {
        //提示添加成功
        toastr.success(response.data.message)
        //模态框隐藏
        $('#addModal').modal('hide')
        //表单重置
        this.reset()
        //下拉框重置
        $(`[name="city"]`).html($(`[name="city"]`).children('option:first-child')[0].outerHTML)
        $(`[name="county"]`).html($(`[name="county"]`).children('option:first-child')[0].outerHTML)
        //刷新学生列表
        getData('/student/list', {})
    }

})

//添加按钮
$('.add-Btn').on('click', () => {
    //更新标题
    $('#addModalLabel').html('录入新学员')
    //重置表单
    $('.add-form')[0].reset()
})

//事件委托 给编辑按钮绑定事件
$('tbody').on('click', 'button', async function (e) {
    //编辑按钮
    if ($(e.target).hasClass('update-btn')) {
        //标题更新
        $('#addModalLabel').html('修改学员')
        //获取学员id
        const id = $(e.target).data('id')
        //发送请求
        const res = await axios({ url: '/student/one', params: { id } })
        //接收对象
        const obj = res.data.data

        //提前给 city 和 coounty 初始化
        await fetchRegion('/geo/city', {
            pname: obj.province
        }, '市', 'city')
        $(`[name="county"]`).html($(`[name="county"]`).children('option:first-child')[0].outerHTML)
        await fetchRegion('/geo/county', {
            pname: obj.province,
            cname: obj.city
        }, '县', 'county')

        //遍历对象 处理数据
        for (const key in obj) {
            //处理数据 非性别选择 刚需元素
            if ($(`[name=${key}]`).length === 1 && key !== 'sex') {
                $(`[name=${key}]`).val(obj[key])
            }
        }
        //处理数据 性别选择
        $(`[name=sex][value=${obj.sex}]`)[0].checked = true

        //开启模态框
        $('#addModal').modal('show')
    }
    //删除按钮
    if ($(e.target).hasClass('del-btn')) {
        //禁用按钮
        $(this)[0].disabled = true
        //获取学员id
        const id = $(e.target).data('id')
        const res = await axios({ url: '/student/delete', method: 'delete', params: { id, } })
        res.data.code === 0 && toastr.success('删除成功', '操作')
        //重渲染学生列表
        getData('/student/list', {})
    }
})
//获取父页面的文档
const child = window.parent.document
console.log(child);
//找到父页面的搜索框 添加点击事件
//获取搜索框
const searchDom = child.querySelector('.top .search input')
//搜索业务
child.querySelector('.top .search button').addEventListener('click', async function () {
    if (!searchDom.value.trim()) return getData('/student/list', {})
    if (isNaN(+searchDom.value.trim())) return toastr.info('仅支持ID搜索...')
    const id = +searchDom.value
    //筛选
    const res = await getData('/student/one', { id })
    //提示
    toastr.success('完成检索')
})
searchDom.onkeyup = (e) => {
    if (e.keyCode !== 13) return
    child.querySelector('.top .search button').click()
}


